//db
const db = require('../db/index')
//formidable
const formidable = require('formidable')
//
const path = require('path')
//
const fs = require('fs')
//bcryptjs
const bcryptjs = require('bcryptjs')

const getUserInfo = (req, res) => {
    res.send({
        status: 200,
        message: '获取用户消息成功！',
        data: {
            mg_name: req.user.mg_name,
            mg_avatar: req.user.mg_avatar
        }
    })
}

//获取用户列表
const getUserList = (req, res) => {
    console.log(req.query);
    let sql =
        !req.query.keyword ? 'select mg_id,mg_name,mg_email,mg_mobile,mg_avatar,mg_state,role_name,mg_del,sp_manager.role_id from sp_manager,sp_role where sp_manager.role_id=sp_role.role_id and mg_del=0'
            : `select mg_id,mg_name,mg_email,mg_mobile,mg_avatar,mg_state,role_name,mg_del,sp_manager.role_id from sp_manager,sp_role where sp_manager.role_id=sp_role.role_id and mg_del=0 and mg_name like '%${req.query.keyword}%'`
    db.query(sql, (err, result) => {
        if (err) return res.sendErr(err)
        // if (result.length === 0) return res.sendErr('不存在用户!')
        const userList = []
        let index = (req.query.currentPage - 1) * (req.query.pageNum - 0)
        let pageNum = index + (req.query.pageNum - 0)
        while (index < pageNum && index < result.length) {
            // console.log(index, index + (req.query.pageNum - 0));
            userList.push(result[index])
            index++
        }
        // console.log(result);
        res.send({
            status: 200,
            data: {
                totalNum: result.length,
                userList: userList
            }
        })
    })
}

//添加用户
const addUser = (req, res) => {
    // console.log();
    var form = new formidable.IncomingForm();
    form.uploadDir = path.join(__dirname, '../coverImg') // 上传目录
    form.parse(req, function (error, fields, files) {
        if (error) return res.sendErr(error)
        // console.log("fields", fields);// fields 除了图片外的信息
        // console.log("files", files);  // files 图片信息

        //存放新用户信息
        const userInfo = fields
        userInfo.mg_state = 0
        userInfo.role_id = 42 //超管
        userInfo.mg_time = Number(Date.now() + "")
        // userInfo.mg_time = 1486720211
        //上传了头像
        if (JSON.stringify(files) !== "{}") {
            // 文件重命名（保存文件）
            let originalFilename = files['mg_avatar'].originalFilename  //文件原始的名称 如01.jpg
            let extName = path.extname(originalFilename)    //.jpg
            let baseName = path.basename(originalFilename, extName)  //o1
            let newName = baseName + '-' + Date.now() + extName;
            let oldPath = files['mg_avatar'].filepath
            fs.rename(oldPath, path.join(__dirname, '../coverImg', `${newName}`), (err) => {
                if (err) {
                    return res.sendErr('上传失败(重命名失败！)')
                }
            })
            userInfo.mg_avatar = "http://localhost:3006/api/" + newName

            //密码加密（bcryptjs.hashSync）(10表示随机盐长度)
            userInfo.mg_pwd = bcryptjs.hashSync(userInfo.mg_pwd, 10)
        }
        //插入信息到数据库
        let sql = 'insert into sp_manager set ?'
        db.query(sql, userInfo, (err, result) => {
            if (err) return res.sendErr(err)
            if (result.affectedRows !== 1) {
                return res.sendErr("添加失败!")
            }
            res.send({
                status: 200,
                message: "添加成功!",
                data: userInfo
            })
        })
    })
}

//更改用户信息
//1 辅助函数，存入数据库
let updateToDb = (res, role_name, newUserInfo) => {
    // console.log(123123, role_name, newUserInfo);
    new Promise((resolve, reject) => {
        //role_name替换为role_id
        let sql = 'select role_id from sp_role where role_name=?'
        db.query(sql, role_name, (err, result) => {
            if (err) reject(err)
            if (result.length === 0) reject("更改的该role_name找不到对应的role_id")
            //找到了role_id
            newUserInfo['role_id'] = result[0].role_id
            resolve(res)
        })
    }).then(res => {
        // 插入newUserInfo
        sql = 'update sp_manager set ? where mg_id=?'
        // mg_id   mg_state     mg_email,mg_mobile，mg_avatar    role_id     mg_del(删除的) 
        db.query(sql, [newUserInfo, newUserInfo.mg_id], (err, result) => {
            if (err) return res.sendErr(err)
            if (result.affectedRows !== 1) return res.sendErr("更改失败!")
            //成功
            res.send({
                status: 200,
                message: "更新成功!"
            })
        })
    }, err => {
        return res.sendErr(err)
    })
}
//2 逻辑函数
const updateUserInfo = (req, res) => {
    // console.log(req.body);
    //如果上传了图片(formdata)
    if (JSON.stringify(req.body) === "{}") {
        console.log("含头像更新");
        var form = new formidable.IncomingForm();
        form.uploadDir = path.join(__dirname, '../coverImg') // 上传目录
        form.parse(req, function (error, fields, files) {
            if (error) return res.sendErr(error)
            let { role_name, ...newUserInfo } = fields
            // 上传的头像
            let originalFilename = files['mg_avatar'].originalFilename  //文件原始的名称 如01.jpg
            let extName = path.extname(originalFilename)    //.jpg
            let baseName = path.basename(originalFilename, extName)  //o1
            let newName = baseName + '-' + Date.now() + extName;
            let oldPath = files['mg_avatar'].filepath
            fs.rename(oldPath, path.join(__dirname, '../coverImg', `${newName}`), (err) => {
                if (err) {
                    return res.sendErr('上传失败(重命名失败！)')
                }
            })
            newUserInfo.mg_avatar = "http://localhost:3006/api/" + newName
            //调用函数
            updateToDb(res, role_name, newUserInfo)
        })
    }
    //上传的不是formdata 正常的body
    else {
        console.log("无头像更新");
        let { role_name, ...newUserInfo } = req.body
        updateToDb(res, role_name, newUserInfo)
    }
}

module.exports = {
    getUserInfo,
    addUser,
    getUserList,
    updateUserInfo
}